package com.ztx.access;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;
@Component

public class UserRoleMapping {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private SetOperations<String, Object> setOperations;

    @PostConstruct
    public void init() {
        this.setOperations = redisTemplate.opsForSet();
    }

    public void addRoleToUser(Long userId, String role) {
        setOperations.add("user:" + userId, role);
    }

    public void removeRoleFromUser(Long userId, String role) {
        setOperations.remove("user:" + userId, role);
    }

    public Set<Object> getRolesForUser(Long userId) {
        return setOperations.members("user:" + userId);
    }

    public boolean hasRole(Long userId,Object role) {
        Set<Object> roles = setOperations.members("user:" + userId);
        return roles.contains(role);
    }
}